package com.nicolas.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import org.wltea.analyzer.lucene.IKAnalyzer;

/**
 * txt文件索引
 * 
 * @author
 */
public class IndexFile {

	private Directory directory;

	private static final File INDEX_PATH = new File(System
			.getProperty("user.dir")
			+ "\\index"); // 索引文件位置,
	private static final String filePath = System.getProperty("user.dir")
			+ "\\searchfiles";//

	private Analyzer analyzer = new IKAnalyzer();

	private IndexWriter indexWriter;

	private boolean inited = false;

	public boolean isInit() {

		return inited;
	}

	public boolean init() {
		try {
			directory = FSDirectory.open(INDEX_PATH);
			indexWriter = getIndexWriter(directory);
		} catch (Exception e) {
			System.out.println("索引打开异常！");
		}
		return inited = true;
	}

	/**
	 * 获得所有txt文件
	 * 
	 * @param dirPath
	 * @return
	 */
	public List<File> getFileList(String dirPath) {
		File[] files = new File(dirPath).listFiles();
		List<File> fileList = new ArrayList<File>();
		for (File file : files) {
			if (isTxtFile(file.getName())) {
				fileList.add(file);
			}
		}
		return fileList;
	}

	/**
	 * 创建索引
	 * 
	 * @throws Exception
	 */
	public void createIndex() throws Exception {
		List<File> fileList = getFileList(filePath);
		Document document = null;
		for (File file : fileList) {
			document = fileToDocument(file);
			indexWriter.addDocument(document);
			System.out.println("filename==" + document.get("filename"));
			indexWriter.commit();
		}
		closeWriter();
	}

	/**
	 * 判断是否是txt文件
	 * 
	 * @param fileName
	 * @return
	 */
	public boolean isTxtFile(String fileName) {
		if (fileName.lastIndexOf(".txt") > 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否已经创建索引
	 * 
	 * @return
	 */
	public boolean noIndex() {
		File[] indexs = INDEX_PATH.listFiles();
		if (indexs.length == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 将文件转换成Document对象
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public Document fileToDocument(File file) throws Exception {
		Document document = new Document();
		document.add(new TextField("filename", file.getName(), Store.YES));
		document.add(new TextField("content", getFileContent(file), Store.YES));
		document.add(new LongField("size", file.getTotalSpace(), Store.YES));
		return document;
	}

	/**
	 * 获得indexwriter对象
	 * 
	 * @param dir
	 * @return
	 * @throws Exception
	 */
	public IndexWriter getIndexWriter(Directory dir) throws Exception {
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,
				analyzer);
		return new IndexWriter(dir, iwc);
	}

	/**
	 * 关闭indexwriter对象
	 * 
	 * @throws Exception
	 */
	public void closeWriter() throws Exception {
		if (indexWriter != null) {
			indexWriter.close();
		}
	}

	/**
	 * 读取文件内容
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public String getFileContent(File file) throws Exception {
		Reader reader = new InputStreamReader(new FileInputStream(file),
				"UTF-8");
		BufferedReader br = new BufferedReader(reader);
		String result = "";
		String myreadline = "";
		while (br.ready()) {
			myreadline = br.readLine();
			result = result + "\n" + myreadline;
		}

		br.close();
		reader.close();
		return result;
	}

	
	public void search(String feild,String key){
		try {
			//取得索引目录
			IndexReader iReader = DirectoryReader.open(FSDirectory.open(INDEX_PATH));
			IndexSearcher iSearcher = new IndexSearcher(iReader);
			QueryParser qp = new QueryParser(Version.LUCENE_40, feild,
					analyzer);
			qp.setDefaultOperator(QueryParser.AND_OPERATOR);
			Query query = qp.parse(key);
			TopScoreDocCollector collector = TopScoreDocCollector.create(100,
					true);
			iSearcher.search(query, collector);
			ScoreDoc[] hits = collector.topDocs().scoreDocs;
			if (hits.length > 0) {
				System.out.println("检索词：" + key + "\t共找到 " + hits.length
						+ "条记录");
				for (int i = 0; i < hits.length; i++) {
					Document result = iSearcher.doc(hits[i].doc);
					System.out.println((i + 1) + ")" + "\n  index:"
							+ result.get("filename") + "\n  contents:"
							+ result.get("content"));
				}
			} else {
				System.out.println("未找到结果");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		
	} 
	
	public static void main(String[] args) throws Exception {
		IndexFile ifile = new IndexFile();
		if (!ifile.isInit()) {
			ifile.init();
		}
		System.out.println(INDEX_PATH.canWrite());
	//	ifile.createIndex();
		ifile.search("content", "系统");

	}
}
